#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <string.h>
#include <pthread.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
#include <stdbool.h>
# include <termio.h>
# include <fcntl.h>
# include <getopt.h>
#define MAX_LEN 100

void readuci(char cmd[], char para[]) //从uci命令中获取参数
{
	FILE *fp;
	int i = 0;
	if((fp = popen(cmd,"r")) == NULL)
	{
		printf("Get serviceid false!,cmd=%s,para=%s\n",cmd,para);
		sprintf(para,"%s","00000000");
		return;
	}
	memset(para,0,sizeof(para));
	if(fgets(para,MAX_LEN, fp)!=NULL)
	{
		while(para[i] != '\n')
		{
			i++;
		}
		para[i] = '\0';
	}
	pclose(fp);
}


int main()
{
	sleep(5);
	system("killall client");
	system("killall directconnect");
	system("killall edge");
	system("killall relayvpn");
	system("killall openvpn");
	char delay[MAX_LEN];
	char loss[MAX_LEN];
	char delayfluctuate[MAX_LEN];
	readuci("uci get routedif.@routedif[0].delay",delay);
	readuci("uci get routedif.@routedif[0].fluctuation",delayfluctuate);
	readuci("uci get routedif.@routedif[0].loss",loss);	
	char cmd1[MAX_LEN];
	char cmd2[MAX_LEN];
	char cmd3[MAX_LEN];


	strcpy(cmd1,"tc qdisc add dev eth0 root netem delay 1ms");
	sprintf(cmd2,"tc qdisc change dev eth0 root netem delay %sms %sms loss %s%%",delay,delayfluctuate,loss);
	strcpy(cmd3,"/usr/sbin/brctl addif br-lan eth0");

	system(cmd1);
	sleep(1);
	system(cmd2);
	system(cmd3);

	return 0;
}

